const EC = require('../comm/err-code');
const DEV_TABLE = 'big_device';
const DEV_LOG_TAB = 'big_log';

/**
 * 设备数据模型
 */
module.exports = class Dev extends require('./model_pool')
{
  // 查找设备
  static find(DevId){
    return new Promise((resolve,reject)=>{
      let sql='SELECT * FROM '+DEV_TABLE+' WHERE hwid=?';
      this.query(sql, [DevId]).then((results)=>{
          resolve(results[0]);
      }).catch((err)=>{
          console.log('find query faild: ' + err.message)
          reject(0);
      })
    })
  }

  // 通过连接id查找设备
  static findByConnId(connId){
    return new Promise((resolve,reject) => {
      let sql = 'SELECT * FROM '+DEV_TABLE+' WHERE conn_id=?';
      this.query(sql,[connId]).then((results)=>{
          resolve(results);
      }).catch(err => {
          console.log('findByConnId query faild: ' + err.message)
          reject(err);
      })
    })
  }

  // 获取所有
  static getAllDev(page=1, limit=20) {
    page = (page < 1) ? 1 : page;
    return new Promise((resolve,reject) => {
      let sql = 'SELECT * FROM '+DEV_TABLE+' ORDER BY `time` DESC limit ?,?';
      this.query(sql, [(page-1)*parseInt(limit), parseInt(limit)]).then((res)=>{
          resolve(res);
      }).catch(err => {
          console.log('findByConnId query faild: ' + err.message)
          reject(err);
      })
    })
  }

  // 获取自己的设备信息
  static getMyAllDevsInfo(uid) {
    return new Promise((resolve,reject) => {
      let sql = 'SELECT * FROM '+DEV_TABLE+' WHERE uid=?';
      this.query(sql, [uid]).then((res)=>{
        resolve(res);
      }).catch(err => {
        console.log('getMyAllDevsInfo query faild: ' + err.message)
        reject(err);
      })
    })
  }

  // 获取自己的设备数量
  static getMyAllDevsNum(uid) {
    return new Promise((resolve,reject) => {
      let sql = 'SELECT COUNT(hwid) FROM '+DEV_TABLE+' WHERE uid=?';
      this.query(sql, [uid]).then((res)=>{
        resolve(res[0]['COUNT(hwid)']);
      }).catch(err => {
        console.log('getMyAllDevsNum query faild: ' + err.message)
        reject(err);
      })
    })
  }

  // 更新设备属性
  static updateDev(DevId, fields){
    return new Promise((resolve,reject)=>{
      let kvArray = [];
      for (let key in fields) {
        let value = fields[key];
        kvArray.push('`'+key+'`='+`\'${value}\'`);
      }
      let sql = 'UPDATE '+DEV_TABLE+' SET '+kvArray.join(',')+' WHERE hwid=?';
      this.query(sql, [DevId]).then((results)=>{
          resolve(results.affectedRows);
      }).catch(err=>{
          console.log('update Dev faild: ' + err.message)
          reject(0);
      })
    })
  }

  // 批量更新子设备属性
  static updateDevByParent(ParentId, fields){
    return new Promise((resolve,reject)=>{
      let kvArray = [];
      for (let key in fields) {
        let value = fields[key];
        kvArray.push('`'+key+'`='+`\'${value}\'`);
      }
      let sql = 'UPDATE '+DEV_TABLE+' SET '+kvArray.join(',')+' WHERE conn_id=?';
      this.query(sql,[ParentId+'']).then((results)=>{
          resolve(results.affectedRows);
      }).catch(err=>{
          console.log('update Dev faild: ' + err.message)
          reject(0);
      })
    })
  }

  // 新增设备
  static newDev(devId, devType, ip=null, connId=null) {
    return new Promise((resolve,reject) => {
      let sql = 'INSERT INTO '+DEV_TABLE+' (hwid,hwtype,ip,conn_id,online,first,expire) VALUES(?,?,?,?,0,CURDATE(),DATE_ADD(CURDATE(),INTERVAL 1 YEAR))';
      this.query(sql, [devId, devType, ip, connId]).then((results)=>{
          resolve(results.affectedRows);
      }).catch(err=>{
          console.log('newDev insert faild: ' + err.message)
          reject(0);
      })
    })
  }

  // 新增用户设备
  static newUserDev(uid, devId, devType) {
    return new Promise((resolve,reject) => {
      let sql = `INSERT INTO ${DEV_TABLE} (hwid,uid,hwtype,online,first,expire) VALUES(?,?,?,0,CURDATE(),DATE_ADD(CURDATE(),INTERVAL 1 YEAR))`;
      this.query(sql, [devId, uid, devType]).then((results)=>{
          resolve(results.affectedRows);
      }).catch(err=>{
        if (err.errno == EC.ER_DUP_ENTRY) {
          resolve(0);
          return;
        } if (err.errno == EC.ER_NO_REFERENCED_ROW_2) { // uid外键不对，新建主表记录，todo 权限是否允许

        }
        console.log('newUserDev insert faild: ' + err.message)
        reject(0);
      })
    })
  }

  // 现存设备上线
  static online(DevId, ip, connId=null) {
    return new Promise((resolve,reject) => {
      let sql = 'UPDATE '+DEV_TABLE+' SET ip=?, conn_id=?, online=1, last=Now() WHERE hwid=?';
      this.query(sql, [ip, connId, DevId]).then((results)=>{
          resolve(results.affectedRows);
      }).catch(err => {
          console.log('Online update faild: ' + err.message)
          reject(0);
      })
    })
  }

  // 设备下线
  static offline(DevId, connIdKeep=false) {
    return new Promise((resolve,reject) => {
      let sql = 'UPDATE '+DEV_TABLE+' SET conn_id=null, online=0, last=Now() WHERE hwid=?';
      if(connIdKeep) sql = 'UPDATE '+DEV_TABLE+' SET online=0, last=Now() WHERE hwid=?';
      this.query(sql,[DevId]).then((results)=>{
          resolve(results.affectedRows);
      }).catch((err)=>{
          console.log('Offline update faild: ' + err.message)
          reject(0);
      })
    })
  }

  // 初始化所有设备在线标记
  static offlineAllDev() {
    return new Promise((resolve,reject)=>{
      let sql = 'UPDATE '+DEV_TABLE+' SET online=0';
      this.query(sql).then((results)=>{
          resolve(results.affectedRows);
      }).catch(err => {
          console.log('Offline update faild: ' + err.message)
          reject(0);
      })
    })
  }

  // log 表函数
  // 获取设备log总数
  static getDevLogsTotal(uid, DevId) {
    return new Promise((resolve,reject)=>{
      let sql = 'SELECT COUNT(id) AS total FROM '+DEV_LOG_TAB+' WHERE uid=? AND hwid=?';
      this.query(sql, [uid, DevId]).then((results)=>{
          resolve(results[0].total);
      }).catch(err => {
          console.log('Offline update faild: ' + err.message)
          reject(0);
      })
    })
  }

  // log 表函数
  // 获取设备log信息
  static getDevLogs(uid, DevId, page = 1, limit = 20) {
    page = (page < 1) ? 1 : page;
    return new Promise((resolve,reject)=>{
      let sql = 'SELECT * FROM '+DEV_LOG_TAB+' WHERE uid=? AND hwid=? ORDER BY `time` DESC limit ?,?';
      this.query(sql, [uid, DevId, (page-1)*parseInt(limit), parseInt(limit)]).then((results)=>{
          resolve(results);
      }).catch(err => {
          console.log('get dev logs faild: ' + err.message)
          reject(0);
      })
    })
  }

  // log 表函数
  // 清除设备log信息
  static cleanDevLogs(uid, DevId) {
    return new Promise((resolve,reject)=>{
      let sql = 'DELETE FROM '+DEV_LOG_TAB+' WHERE uid=? AND hwid=?';
      this.query(sql,[uid, DevId]).then((results)=>{
          resolve(results.affectedRows);
      }).catch(err => {
          console.log('clean Dev logs faild: ' + err.message)
          reject(0);
      })
    })
  }

}